package br.fatec.ppi.projeto.repositorios;

import br.fatec.ppi.projeto.Endereco;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Vânia Angelotti RA: 1430431112040
 */
public class EnderecoRepositorio {

    private EntityManager manager;
    private EntityTransaction tran;

    public EnderecoRepositorio() {
        manager = Persistence.createEntityManagerFactory("modelo").createEntityManager();
        tran = manager.getTransaction();
    }

    public boolean salvar(Endereco endereco) {
        try {
            tran.begin();
            manager.persist(endereco);
            tran.commit();
            return true;
        } catch (Exception e) {
            tran.rollback();
            return false;
        }
    }

    public boolean atualizar(Endereco endereco) {
        try {
            tran.begin();
            manager.merge(endereco);
            tran.commit();
            return true;
        } catch (Exception e) {
            tran.rollback();
            return false;
        }
    }

    public boolean deletar(Endereco endereco) {
        try {
            tran.begin();
            manager.remove(endereco);
            tran.commit();
            return true;
        } catch (Exception e) {
            tran.rollback();
            return false;
        }
    }

    public Endereco getById(int id) {
        Query query = manager.createQuery("SELECT e FROM Endereco e WHERE e.idEndereco = :idEndereco");
        query.setParameter("idEndereco", id);

        List<Endereco> listEndereco = query.getResultList();
        if (listEndereco.isEmpty()) {
            return null;
        }

        return listEndereco.get(0);
    }
}
